import React, { useEffect, useState } from 'react';
import {
  Card,
  Typography,
  Row,
  Col,
  Descriptions,
  Table,
  Tag,
  Button,
  Space,
  Steps,
  Timeline,
  Image,
  Divider,
  message,
  Modal,
  Form,
  Input,
  Select,
  Spin,
} from 'antd';
import {
  PrinterOutlined,
  EditOutlined,
  TruckOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  PhoneOutlined,
  EnvironmentOutlined,
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';

const { Title, Text, Paragraph } = Typography;
const { Step } = Steps;
const { Option } = Select;

// 订单商品接口
interface OrderItem {
  id: string;
  productId: string;
  productName: string;
  productImage: string;
  price: number;
  quantity: number;
  specifications?: Record<string, string>;
}

interface Order {
  id: string;
  orderNo: string;
  userId: string;
  userName: string;
  userAvatar?: string;
  shopId: string;
  shopName: string;
  items: OrderItem[];
  totalAmount: number;
  discountAmount: number;
  shippingFee: number;
  finalAmount: number;
  status: 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled' | 'refunded';
  paymentMethod: 'alipay' | 'wechat' | 'credit_card' | 'cash';
  paymentStatus: 'unpaid' | 'paid' | 'refunded';
  shippingAddress: {
    name: string;
    phone: string;
    address: string;
  };
  trackingNumber?: string;
  remark?: string;
  createdAt: string;
  updatedAt: string;
  paidAt?: string;
  shippedAt?: string;
  deliveredAt?: string;
}

interface LogisticsInfo {
  time: string;
  status: string;
  location?: string;
}

const OrderDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();

  const [order, setOrder] = useState<Order | null>(null);
  const [logistics, setLogistics] = useState<LogisticsInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusModalVisible, setStatusModalVisible] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '订单管理', path: '/orders' },
      { title: '订单列表', path: '/orders' },
      { title: `订单详情` },
    ]));
  }, [dispatch]);

  // 加载订单详情
  useEffect(() => {
    if (id) {
      loadOrderDetail();
    }
  }, [id]);

  const loadOrderDetail = async () => {
    try {
      setLoading(true);

      // 从API获取真实订单数据
      const response = await fetch(`http://localhost:3002/api/admin/orders/${id}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('admin_token')}`,
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error('获取订单详情失败');
      }

      const result = await response.json();
      const orderData = result.data;

      // 转换API数据格式为组件需要的格式
      const transformedOrder: Order = {
        id: orderData._id,
        orderNo: orderData.orderNo,
        userId: orderData.userId,
        userName: orderData.userName,
        userAvatar: orderData.userAvatar || 'https://via.placeholder.com/32x32',
        shopId: orderData.shopId || '',
        shopName: orderData.shopName || '未知店铺',
        items: orderData.orderItems?.map((item: any) => ({
          id: item.id,
          productId: item.productId,
          productName: item.name,
          productImage: item.image || 'https://via.placeholder.com/80x80/f0f0f0/999999?text=商品',
          price: item.price,
          quantity: item.quantity,
          specifications: item.specifications || {},
        })) || [],
        totalAmount: orderData.totalPrice,
        discountAmount: 0,
        shippingFee: 0,
        finalAmount: orderData.totalPrice,
        status: orderData.orderStatus,
        paymentMethod: orderData.paymentMethod || '未选择',
        paymentStatus: orderData.isPaid ? 'paid' : 'unpaid',
        shippingAddress: orderData.shippingAddress ? {
          name: orderData.shippingAddress.name,
          phone: orderData.shippingAddress.phone,
          address: `${orderData.shippingAddress.province}${orderData.shippingAddress.city}${orderData.shippingAddress.district}${orderData.shippingAddress.address}`,
        } : {
          name: '未填写',
          phone: '未填写',
          address: '未填写',
        },
        trackingNumber: orderData.trackingNumber || '',
        remark: orderData.remark || '',
        createdAt: orderData.createdAt,
        updatedAt: orderData.updatedAt,
        paidAt: orderData.paidAt,
        shippedAt: orderData.deliveredAt,
      };

      // 模拟物流信息（如果后端没有提供的话）
      const mockLogistics: LogisticsInfo[] = [
        {
          time: new Date(orderData.createdAt).toLocaleString('zh-CN'),
          status: '订单创建',
          location: '系统',
        },
      ];

      if (orderData.isPaid && orderData.paidAt) {
        mockLogistics.push({
          time: new Date(orderData.paidAt).toLocaleString('zh-CN'),
          status: '付款确认',
          location: '系统',
        });
      }

      if (orderData.orderStatus === '已发货' && orderData.deliveredAt) {
        mockLogistics.push({
          time: new Date(orderData.deliveredAt).toLocaleString('zh-CN'),
          status: '商品已发货',
          location: '发货仓库',
        });
      }

      if (orderData.orderStatus === '已完成') {
        mockLogistics.push({
          time: new Date(orderData.updatedAt).toLocaleString('zh-CN'),
          status: '订单完成',
          location: '系统',
        });
      }

      setOrder(transformedOrder);
      setLogistics(mockLogistics);
    } catch (error) {
      console.error('加载订单详情失败:', error);
      message.error('加载订单详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取订单状态标签
  const getStatusTag = (status: string) => {
    const statusConfig = {
      '待付款': { color: 'orange', text: '待付款' },
      '待发货': { color: 'blue', text: '待发货' },
      '已发货': { color: 'cyan', text: '已发货' },
      '已完成': { color: 'green', text: '已完成' },
      '已取消': { color: 'red', text: '已取消' },
      '已退款': { color: 'purple', text: '已退款' },
      '退款中': { color: 'purple', text: '退款中' },
      // 兼容英文状态
      pending: { color: 'orange', text: '待付款' },
      paid: { color: 'blue', text: '已付款' },
      shipped: { color: 'cyan', text: '已发货' },
      delivered: { color: 'green', text: '已完成' },
      cancelled: { color: 'red', text: '已取消' },
      refunded: { color: 'purple', text: '已退款' },
    };
    const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取支付方式标签
  const getPaymentMethodTag = (method: string) => {
    const methodConfig = {
      alipay: { color: 'blue', text: '支付宝' },
      wechat: { color: 'green', text: '微信支付' },
      credit_card: { color: 'gold', text: '信用卡' },
      cash: { color: 'default', text: '现金' },
    };
    const config = methodConfig[method as keyof typeof methodConfig] || { color: 'default', text: method };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取订单步骤
  const getOrderSteps = (order: Order) => {
    const steps = [
      { title: '订单创建', status: 'finish', time: order.createdAt },
      { title: '付款确认', status: order.paidAt ? 'finish' : 'wait', time: order.paidAt },
      { title: '商品发货', status: order.shippedAt ? 'finish' : 'wait', time: order.shippedAt },
      { title: '订单完成', status: order.deliveredAt ? 'finish' : 'wait', time: order.deliveredAt },
    ];

    if (order.status === 'cancelled') {
      return [
        { title: '订单创建', status: 'finish', time: order.createdAt },
        { title: '订单取消', status: 'error', time: order.updatedAt },
      ];
    }

    return steps;
  };

  // 更新订单状态
  const handleUpdateStatus = async (values: any) => {
    try {
      // await OrderService.updateOrderStatus(id!, values);
      message.success('订单状态更新成功');
      setStatusModalVisible(false);
      loadOrderDetail();
    } catch (error) {
      message.error('更新失败');
    }
  };

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '400px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!order) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Text type="secondary">订单不存在</Text>
      </div>
    );
  }

  const steps = getOrderSteps(order);
  const currentStep = steps.findIndex(step => step.status === 'wait');

  // 商品表格列定义
  const itemColumns = [
    {
      title: '商品信息',
      key: 'product',
      render: (item: OrderItem) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Image
            src={item.productImage || 'https://via.placeholder.com/60x60/f0f0f0/999999?text=商品'}
            alt={item.productName}
            width={60}
            height={60}
            style={{ borderRadius: 4, marginRight: 12, objectFit: 'cover' }}
            fallback="https://via.placeholder.com/60x60/f0f0f0/999999?text=商品"
            onError={(e) => {
              e.currentTarget.src = 'https://via.placeholder.com/60x60/f0f0f0/999999?text=商品';
            }}
          />
          <div>
            <div style={{ fontWeight: 500, marginBottom: 4 }}>
              {item.productName}
            </div>
            {item.specifications && Object.keys(item.specifications).length > 0 && (
              <div style={{ fontSize: 12, color: '#666' }}>
                {Object.entries(item.specifications).map(([key, value]) => (
                  <span key={key} style={{ marginRight: 8 }}>
                    {key}: {value}
                  </span>
                ))}
              </div>
            )}
          </div>
        </div>
      ),
    },
    {
      title: '单价',
      dataIndex: 'price',
      key: 'price',
      width: 100,
      render: (price: number) => `¥${price.toFixed(2)}`,
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 80,
    },
    {
      title: '小计',
      key: 'subtotal',
      width: 100,
      render: (item: OrderItem) => `¥${(item.price * item.quantity).toFixed(2)}`,
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 订单基本信息 */}
      <Card style={{ marginBottom: '24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
          <div>
            <Title level={3} style={{ margin: 0, marginBottom: '8px' }}>
              订单详情 - {order.orderNo}
            </Title>
            <Space>
              {getStatusTag(order.status)}
              {getPaymentMethodTag(order.paymentMethod)}
              <Text type="secondary">
                创建时间: {new Date(order.createdAt).toLocaleString()}
              </Text>
            </Space>
          </div>
          <Space>
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={() => setStatusModalVisible(true)}
            >
              更新状态
            </Button>
            <Button icon={<PrinterOutlined />}>
              打印订单
            </Button>
          </Space>
        </div>

        {/* 订单进度 */}
        <Steps
          current={currentStep === -1 ? steps.length - 1 : currentStep}
          style={{ marginBottom: '24px' }}
        >
          {steps.map((step, index) => (
            <Step
              key={index}
              title={step.title}
              status={step.status as any}
              description={step.time ? new Date(step.time).toLocaleString() : undefined}
            />
          ))}
        </Steps>

        {/* 基本信息 */}
        <Row gutter={24}>
          <Col span={12}>
            <Descriptions title="订单信息" bordered column={1} size="small">
              <Descriptions.Item label="订单编号">{order.orderNo}</Descriptions.Item>
              <Descriptions.Item label="订单状态">{getStatusTag(order.status)}</Descriptions.Item>
              <Descriptions.Item label="支付方式">{getPaymentMethodTag(order.paymentMethod)}</Descriptions.Item>
              <Descriptions.Item label="支付状态">
                <Tag color={order.paymentStatus === 'paid' ? 'green' : 'orange'}>
                  {order.paymentStatus === 'paid' ? '已支付' : '未支付'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="物流单号">
                {order.trackingNumber || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="备注">
                {order.remark || '-'}
              </Descriptions.Item>
            </Descriptions>
          </Col>
          <Col span={12}>
            <Descriptions title="用户信息" bordered column={1} size="small">
              <Descriptions.Item label="用户姓名">{order.userName}</Descriptions.Item>
              <Descriptions.Item label="用户ID">{order.userId}</Descriptions.Item>
              <Descriptions.Item label="收货人">{order.shippingAddress.name}</Descriptions.Item>
              <Descriptions.Item label="联系电话">
                <Space>
                  <PhoneOutlined />
                  {order.shippingAddress.phone}
                </Space>
              </Descriptions.Item>
              <Descriptions.Item label="收货地址">
                <Space>
                  <EnvironmentOutlined />
                  {order.shippingAddress.address}
                </Space>
              </Descriptions.Item>
              <Descriptions.Item label="店铺">{order.shopName}</Descriptions.Item>
            </Descriptions>
          </Col>
        </Row>
      </Card>

      {/* 商品信息 */}
      <Card title="商品信息" style={{ marginBottom: '24px' }}>
        <Table
          columns={itemColumns}
          dataSource={order.items}
          rowKey="id"
          pagination={false}
          size="small"
        />

        <Divider />

        <Row justify="end">
          <Col span={8}>
            <div style={{ textAlign: 'right' }}>
              <div style={{ marginBottom: '8px' }}>
                <Text>商品总额: </Text>
                <Text strong>¥{order.totalAmount.toFixed(2)}</Text>
              </div>
              {order.discountAmount > 0 && (
                <div style={{ marginBottom: '8px' }}>
                  <Text>优惠金额: </Text>
                  <Text strong style={{ color: '#52c41a' }}>-¥{order.discountAmount.toFixed(2)}</Text>
                </div>
              )}
              <div style={{ marginBottom: '8px' }}>
                <Text>运费: </Text>
                <Text strong>¥{order.shippingFee.toFixed(2)}</Text>
              </div>
              <div style={{ fontSize: '16px', marginBottom: '8px' }}>
                <Text>实付金额: </Text>
                <Text strong style={{ color: '#f50', fontSize: '18px' }}>
                  ¥{order.finalAmount.toFixed(2)}
                </Text>
              </div>
            </div>
          </Col>
        </Row>
      </Card>

      {/* 物流信息 */}
      {order.trackingNumber && logistics.length > 0 && (
        <Card title={
          <Space>
            <TruckOutlined />
            物流跟踪
            <Tag color="blue">{order.trackingNumber}</Tag>
          </Space>
        }>
          <Timeline>
            {logistics.map((item, index) => (
              <Timeline.Item
                key={index}
                color={index === 0 ? 'green' : 'blue'}
                dot={index === 0 ? <CheckCircleOutlined /> : <ClockCircleOutlined />}
              >
                <div>
                  <div style={{ fontWeight: 500 }}>{item.status}</div>
                  <div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>
                    {item.time} {item.location && `· ${item.location}`}
                  </div>
                </div>
              </Timeline.Item>
            ))}
          </Timeline>
        </Card>
      )}

      {/* 更新状态模态框 */}
      <Modal
        title="更新订单状态"
        open={statusModalVisible}
        onCancel={() => setStatusModalVisible(false)}
        onOk={() => form.submit()}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleUpdateStatus}
          initialValues={{
            status: order.status,
          }}
        >
          <Form.Item
            label="订单状态"
            name="status"
            rules={[{ required: true, message: '请选择订单状态' }]}
          >
            <Select>
              <Option value="pending">待付款</Option>
              <Option value="paid">已付款</Option>
              <Option value="shipped">已发货</Option>
              <Option value="delivered">已完成</Option>
              <Option value="cancelled">已取消</Option>
              <Option value="refunded">已退款</Option>
            </Select>
          </Form.Item>

          <Form.Item label="物流单号" name="trackingNumber">
            <Input placeholder="请输入物流单号" />
          </Form.Item>

          <Form.Item label="备注" name="remark">
            <Input.TextArea rows={3} placeholder="请输入备注信息" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default OrderDetail;
